//
//  CommonPickerView.swift
//  EyeVisionForDoctors
//
//  Created by QDSG on 2020/3/2.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
import HandyJSON

enum CommonPickerViewType: String {
    case relation = "patient_relation" // 与我的关系
    case office = "doc_job_title" // 医生职称
    case drugFrequency = "drug_frequency" // 药品使用频率
    case drugUsing = "drug_route" // 药品使用途径
    case prefix = "diagnose_prefix" // 诊断前缀
    case suffix = "diagnose_suffix" // 诊断后缀
    case diagnose = "diagnose"      // 诊断
    case checkEyeType = "check_eye_type"  // 检查眼别
    
    var title: String {
        switch self {
        case .relation: return "与我的关系"
        case .drugFrequency: return "使用频次"
        case .drugUsing: return "用法"
        case .prefix: return "前缀"
        case .suffix: return "后缀"
        case .diagnose: return "诊断"
        case .checkEyeType: return "选择检查眼别"
        default: return "请选择"
        }
    }
}

class CommonPickerView: UIView {
    
    var selectedClosure: ((_ model: CommonPickerModel) -> Void)?
    
    private var dataSource: [CommonPickerModel] = [] {
        didSet {
            tableView.reloadData()
        }
    }
    
    @IBOutlet private weak var titleLabel: UILabel! {
        didSet {
            titleLabel.textColor = Asset.main.color
        }
    }
    
    @IBOutlet private weak var activityView: UIActivityIndicatorView!
    
    @IBOutlet private weak var contentView: UIView! {
        didSet {
            contentView.layer.cornerRadius = 16
            contentView.layer.masksToBounds = true
            contentView.transform = CGAffineTransform(scaleX: 0.0001, y: 0.0001)
        }
    }

    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.delegate = self
            tableView.dataSource = self
            tableView.rowHeight = 50
            tableView.estimatedRowHeight = UITableView.automaticDimension
            tableView.backgroundColor = .white
            tableView.tableFooterView = UIView()
            tableView.register(UINib(nibName: CommonPickerCell.className, bundle: nil),
                               forCellReuseIdentifier: CommonPickerCell.reuseIdentifier)
        }
    }
    
    @IBAction private func closeAction() {
        dismiss()
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        self.alpha = 0.0
    }
    
    func show(in view: UIView? = nil, type: CommonPickerViewType) {
        let tempView = view == nil ? mainWindow : view
        tempView?.addSubview(self)
        
        titleLabel.text = type.title
        
        UIView.animate(withDuration: 0.25, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: .curveLinear, animations: {
            self.alpha = 1.0
            self.contentView.transform = CGAffineTransform(scaleX: 1, y: 1)
        }) { _ in
            self.loadData(type)
        }
    }
    
    private func dismiss() {
        UIView.animate(withDuration: 0.25, delay: 0, options: .curveLinear, animations: {
            self.contentView.transform = CGAffineTransform(scaleX: 0.0001, y: 0.0001)
        }) { _ in
            self.alpha = 0.0
            self.removeFromSuperview()
        }
    }
    
    private func loadData(_ type: CommonPickerViewType) {
        switch type {
//        case .diagnose:
//            activityView.startAnimating()
//            CommonPickerModel.getDiseaseList(success: { models in
//                self.activityView.stopAnimating()
//                self.dataSource = models
//            }) { errorMsg in
//                self.activityView.stopAnimating()
//                HUDTool.showError(message: errorMsg)
//            }
        case .relation:
            let arr = [
                ["code": 0, "name": "自己"],
                ["code": 1, "name": "父母"],
                ["code": 2, "name": "子女"],
                ["code": 3, "name": "爱人"],
                ["code": 4, "name": "其他"]
            ]
            if let models = JSONDeserializer<CommonPickerModel>.deserializeModelArrayFrom(array: arr) as? [CommonPickerModel] {
                self.dataSource = models
            }
        case .checkEyeType:
            let arr = [
                ["name": "双眼"],
                ["name": "右眼"],
                ["name": "左眼"],
            ]
            if let models = JSONDeserializer<CommonPickerModel>.deserializeModelArrayFrom(array: arr) as? [CommonPickerModel] {
                self.dataSource = models
            }
        default: break
//            activityView.startAnimating()
//            CommonPickerModel.getPickerListData(category: type.rawValue, success: { models in
//                self.activityView.stopAnimating()
//                self.dataSource = models
//            }) { errorMsg in
//                self.activityView.stopAnimating()
//                HUDTool.showError(message: errorMsg)
//            }
        }
    }
}

extension CommonPickerView: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: CommonPickerCell.reuseIdentifier,
                                                 for: indexPath) as! CommonPickerCell
        cell.configure(with: dataSource[indexPath.row])
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = dataSource[indexPath.row]
        dismiss()
        selectedClosure?(model)
    }
}
